from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin

from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from rest_framework.views import APIView

from app01.models import Goods, UserInfo, People
from app01.myform import GoodsForm
from app01.myserializer import GoodsSerializer, PeopleSerializer, UserinfoSerializer
from app01.utils.current_limiting import VisitLimit, UserLimit
from app01.utils.jwt_createa_and_verified import create_token



from rest_framework.pagination import PageNumberPagination, CursorPagination
# class MyPageNumberPagination(PageNumberPagination):
#     """分页类"""
#     # 每页展示多少条数据
#     page_size = 1
#     # 前端可以自己?page=10，取哪一页的数据。
#     page_query_param = 'page'
#     # 前端可以?size=10000自己配置，每页想取多少条自己设置
#     page_size_query_param = 'size'
#     # 最大页码的查询参数名
#     max_page_size = 1000
class MyPageNumberPagination(CursorPagination):
    cursor_query_param = 'page'
    page_size = 1
    ordering = 'id'
    page_size_query_param = None
    max_page_size = None


# @method_decorator(csrf_exempt,name='dispatch')
# class GoodsView1(APIView):
#     authentication_classes = []
#     permission_classes = []
#     throttle_classes = [VisitLimit, ]
#     def get(self, request):
#         # 只取前三条就行了
#         goods = Goods.objects.all()[:3].values('id','name','image','datetime')
#         # 转化为json能序列化的数据类型
#         goods = list(goods)
#         # 如果转列表要加safe=False
#         return JsonResponse(goods,safe=False)
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.generics import ListAPIView,CreateAPIView,RetrieveAPIView,DestroyAPIView,UpdateAPIView
# class GoodsView1(ListAPIView,CreateAPIView,RetrieveAPIView,DestroyAPIView,UpdateAPIView,):
class GoodsView1(CacheResponseMixin,CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericViewSet):
    authentication_classes = []
    permission_classes = []
    throttle_classes = [VisitLimit, UserLimit]
    queryset = Goods.objects.all()    # 指明你的待序列化数据(默认是全部)
    serializer_class = GoodsSerializer #
    pagination_class = MyPageNumberPagination
    versioning_class = None
    # def get(self,request):
    #     """查所有数据或（如果带有id证明是查一个）"""
    #     id = request.query_params.get('id')
    #     if not id:
    #         goods = Goods.objects.all()
    #         serializer = GoodsSerializer(goods,many=True)
    #     else:
    #         goods_obj = get_object_or_404(Goods,id=id)
    #         serializer = GoodsSerializer(goods_obj)
    #     return Response(serializer.data)
    #
    #
    # def post(self,request):
    #     """增接口"""
    #     data = request.data
    #     serializer = GoodsSerializer(data=data)
    #     if serializer.is_valid():
    #         serializer.save()
    #         return Response(serializer.data)
    #     return Response(serializer.errors)
    #
    #
    # def delete(self,request):
    #     """删接口，查单个和这个删除以及更新接口我都是?id=1这样传参，可以统一接口url"""
    #     id = request.query_params.get('id')
    #     if id:
    #         book_obj = get_object_or_404(Goods,id=id)
    #         book_obj.delete()
    #         return Response("删除成功")
    #     return Response("您必须传入待删除的id，不能一次性全删")
    #
    # def update(self,request):
    #     """更新接口"""
    #     id = request.query_params.get('id')
    #     if id:
    #         book_obj = get_object_or_404(Goods, id=id)
    #         # instance是待修改的对象，data是修改的内容
    #         serializer = GoodsSerializer(data=request.data, instance=book_obj, partial=True)  # True表示我们是部分更新
    #         if serializer.is_valid():
    #             serializer.save()
    #             return Response(serializer.data)
    #         return Response(serializer.errors)
    #     return Response("您必须传入待更新的id")


class djangoForm(View):
    """查全部和查单个的接口"""
    def get(self,request):
        form = GoodsForm()
        # 没有传id说明是查全部，有传证明只查一条
        goods_id = request.GET.get('id')
        if not goods_id:
            return render(request,'goods.html',{'form':form})
        # 如果goods_id有值。说明用户只想查一个
        goods_obj = get_object_or_404(Goods,id=goods_id)
        form = GoodsForm(instance=goods_obj)
        return render(request, 'goods.html', {'form': form})


    def post(self,request):
        """增加接口"""
        form = GoodsForm(data=request.POST,files=request.FILES)
        # 为了简便我form中没有定义任何钩子
        if form.is_valid():
            form.save()
            return render(request, 'goods.html', {'form': form,'msg':'添加成功'})

from rest_framework.authentication import SessionAuthentication
class AuthView(APIView):
    """用于用户登录认证，来就给你token，下次拿token去请求另外的接口就认你登录了"""
    authentication_classes = []
    permission_classes = []
    throttle_classes = [VisitLimit,]

    def post(self,request,*args,**kwargs):
        user = request.data.get('username')
        pwd = request.data.get('password')
        try:
            user_obj = UserInfo.objects.filter(username=user,password=pwd).first()
            if not user_obj:
                return JsonResponse({'code':1002,'msg':'用户名或密码错误'})
            token = create_token(user_obj.id,user_obj.username)
            # 用户登录成功，返回这个用户的token
            return JsonResponse({'code':1000,'msg':'登录成功','token':token})
        except:
            return JsonResponse({'code':1001,'msg':'用户登陆异常'})



class DRFView(APIView):
    """全靠手动操作"""
    def get(self,request):
        goods = Goods.objects.all()
        serializer = GoodsSerializer(goods,many=True)
        return Response(serializer.data)

from rest_framework import mixins,generics
class DRFManyView(mixins.ListModelMixin,generics.GenericAPIView):
    """不用写get方法只需指定"""
    queryset = Goods.objects.all()[0:10]
    serializer_class = GoodsSerializer
    # 你不重写就说明不允许get请求(反射)
    def get(self,request):
        return self.list(request)




# TODO: from rest_framework_extensions.cache.mixins import CacheResponseMixin
class DRFManyManyView(generics.ListAPIView,generics.CreateAPIView):
    """最省事+分页"""
    authentication_classes = []
    permission_classes = []
    throttle_classes = [VisitLimit, ]

    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = MyPageNumberPagination


class DRFManyMany2View(generics.ListAPIView,generics.CreateAPIView):
    """最省事+分页"""
    authentication_classes = []  # 登录认证
    permission_classes = []      # 权限
    throttle_classes = [VisitLimit, ]  # 限流

    queryset = Goods.objects.all()    # 指明你的待序列化数据(默认是全部)
    serializer_class = GoodsSerializer #
    pagination_class = MyPageNumberPagination

    def get_queryset(self):
        goods_id = self.request.query_params.get('id')
        if goods_id:
            goods_obj_list = get_list_or_404(Goods,id=goods_id)
            return goods_obj_list
        return self.queryset


from rest_framework import viewsets
# class DRFViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
# class DRFViewSet(mixins.ListModelMixin,):
#
#     authentication_classes = []  # 登录认证
#     permission_classes = []  # 权限
#     throttle_classes = [VisitLimit, ]  # 限流
#
#     queryset = Goods.objects.all()
#     serializer_class = GoodsSerializer
#     pagination_class = MyPageNumberPagination





